package com.xbongbong.helper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.enums.Status;
import com.xbongbong.pojo.TaskDefinition;
import com.xbongbong.util.HeaderUtil;
import com.xbongbong.util.HttpRequestUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 节点定义相关操作
 *
 * @ClassName TaskDefinitionHelper
 * @Author 梁鲁江
 * 创建时间 2022/6/17 9:58
 * 修改时间  2022/6/17 9:58
 **/
@Component
public class TaskDefinitionHelper {
    /**
     * 创建task
     * @param projectCode  项目code
     * @param taskDefinitionJson  节点定义
     * @return
     */
    public static String createTaskDefinition(Long projectCode,String taskDefinitionJson){
//        taskDefinitionJson = "[{\"name\":\"task测试2\",\"version\":1,\"description\":\"\",\"delayTime\":0,\"taskType\":\"SQL\",\"taskParams\":{\"type\":\"CLICKHOUSE\",\"datasource\":1,\"sql\":\"SELECT * from tb_saas_customer_communicate  limit 1\",\"udfs\":\"\",\"sqlType\":\"0\",\"sendEmail\":false,\"displayRows\":10,\"title\":\"\",\"groupId\":null,\"localParams\":[],\"connParams\":\"\",\"preStatements\":[],\"postStatements\":[],\"dependence\":{},\"conditionResult\":{\"successNode\":[],\"failedNode\":[]},\"waitStartTimeout\":{},\"switchResult\":{}},\"flag\":\"YES\",\"taskPriority\":\"MEDIUM\",\"workerGroup\":\"default\",\"failRetryTimes\":0,\"failRetryInterval\":1,\"timeoutFlag\":\"CLOSE\",\"timeoutNotifyStrategy\":null,\"timeout\":0,\"environmentCode\":-1}]";
        JSONObject requestData = new JSONObject();
        requestData.put("taskDefinitionJson",taskDefinitionJson);
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/task-definition";
        //参数格式要求  description=description&projectName=projectName
        String ret = HttpRequestUtils.post(url, requestData);
        JSONObject result = JSON.parseObject(ret);
        Integer code = result.getInteger("code");
        if(Objects.equals(code, Status.SUCCESS.getCode())){
            
        }
        return "";
    }

    public static String createTaskDefinition(Long projectCode,String sql,String sqlType,String name){
        TaskDefinition taskDefinition = JSONObject.parseObject("{\"name\":\"task测试1\",\"version\":1,\"description\":\"\",\"delayTime\":0,\"taskType\":\"SQL\",\"taskParams\":{\"type\":\"CLICKHOUSE\",\"datasource\":1,\"sql\":\"SELECT * from tb_saas_customer_communicate  limit 1\",\"udfs\":\"\",\"sqlType\":\"0\",\"sendEmail\":false,\"displayRows\":10,\"title\":\"\",\"groupId\":null,\"localParams\":[],\"connParams\":\"\",\"preStatements\":[],\"postStatements\":[],\"dependence\":{},\"conditionResult\":{\"successNode\":[],\"failedNode\":[]},\"waitStartTimeout\":{},\"switchResult\":{}},\"flag\":\"YES\",\"taskPriority\":\"MEDIUM\",\"workerGroup\":\"default\",\"failRetryTimes\":0,\"failRetryInterval\":1,\"timeoutFlag\":\"CLOSE\",\"timeoutNotifyStrategy\":null,\"timeout\":0,\"environmentCode\":-1}", TaskDefinition.class);
        taskDefinition.setName(name);
        taskDefinition.getTaskParams().put("sql",sql);
        taskDefinition.getTaskParams().put("sqlType",sqlType);
        JSONObject json = JSONObject.parseObject(JSON.toJSONString(taskDefinition));
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(json);
        return createTaskDefinition(projectCode,jsonArray.toJSONString());
    }

    /**
     * 生成TaskCode
     * @param projectCode
     * @param genNum
     * @return
     */
    public Long genTaskCodeList(Long projectCode,Integer genNum)  {
        String url = HeaderUtil.getHosts()+"/dolphinscheduler/projects/" +
                projectCode +
                "/task-definition/gen-task-codes" ;
        //参数格式要求  description=description&projectName=projectName
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
            List<NameValuePair> list = new ArrayList<>();
            BasicNameValuePair pair = new BasicNameValuePair("genNum", genNum.toString());
            list.add(pair);
            uriBuilder.addParameters(list);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        String ret = HttpRequestUtils.get(HeaderUtil.getHeader(),uriBuilder);
        JSONObject result = JSON.parseObject(ret);
        Integer code = result.getInteger("code");
        if(Objects.equals(code, Status.SUCCESS.getCode())){
            JSONArray data = result.getJSONArray("data");
            Long taskCode = data.getLong(0);
            return taskCode;
        }
        return 0L;
    }

    public  Long genTaskCode(Long projectCode)  {
        return genTaskCodeList(projectCode,1);
    }
    
    
    public static void main(String[] args) {
//        createTaskDefinition(5881692604416L,"");
//        createTaskDefinition(5925630295072L,"SELECT * from tb_saas_customer_communicate  limit 1","0","task测试5");
//        genTaskCodeList(5881692604416L,1);
        JSONObject result = JSON.parseObject("{\"code\":0,\"msg\":\"成功\",\"data\":[5937223100064],\"failed\":false,\"success\":true}");
        JSONArray data = result.getJSONArray("data");
        Long taskCode = data.getLong(0);
    }
}
